package com.ncmmall.api.apis.mall.wechat;


import com.ncmmall.api.apis.service.Result;
import com.ncmmall.api.security.Securitys;
import com.ncmmall.application.business.member.MemberApplication;
import com.ncmmall.application.util.HttpRequests;
import com.ncmmall.cache.redis.RedisService;
import com.feijin.commons.lang.Dates;
import com.feijin.commons.lang.Randoms;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.domain.security.user.WebUserRepository;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Ints;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author likaikai
 * @date 2019-05-13 19:53
 */
@RestController
@RequestMapping("/wechat")
public class WechatApi {

    @Value("${wx.sub_appid}")
    private String appid;

    @Value("${wx.appSecret}")
    private String appSecret;

    private Logger log = LoggerFactory.getLogger(WechatApi.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MemberApplication memberApplication;

    @Autowired
    private WebUserRepository userRepository;

    @Autowired
    private RedisService redisService;

    /**
     * 拖拖部落电商小程序使用，校验code 获取session_key和openid
     *
     * @param code    小程序登录code 临时凭证
     * @param request
     * @return
     */
    @GetMapping("/code")
    public Result code(String code, HttpServletRequest request) {
        Result result = new Result();
        try {
            Requires.isTrue(StringUtils.isNotBlank(code), "code不能为空");

            String body = HttpRequests.get("https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code");

            if (StringUtils.isNotBlank(body)) {

                JSONObject jsonObject = JSONObject.fromObject(body);

                if (jsonObject.get("session_key") != null) {

                    String sessionKey = jsonObject.get("session_key").toString();
                    String openId = jsonObject.get("openid").toString();

                    if (Securitys.isLogin(request)) {
                        WebUser member = Securitys.user(request);
                        member.setOpenId(openId);
                        member.setWechatSessionKey(sessionKey);
                        userRepository.save(member);
                    }

                    return result.ok().inject(ImmutableMap.of("openId", openId, "sessionKey", sessionKey));
                }

                int errcode = Ints.tryParse(jsonObject.getString("errcode"));
                switch (errcode) {
                    case -1:
                        result.fail().setMsg("系统繁忙");
                        break;
                    case 40029:
                        result.fail().setMsg("code无效");
                        break;
                    case 40163:
                        result.fail().setMsg("code已被使用");
                        break;
                    case 45011:
                        result.fail().setMsg("频率限制，每个用户每分钟100次");
                        break;
                    default:
                        result.fail().setMsg(jsonObject.get("errmsg").toString());
                        break;
                }
                return result;
            } else {
                return result.fail().setMsg("微信响应为空");
            }
        } catch (IllegalArgumentException e) {
            log.error(e.getMessage(), e);
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取数据异常", e);
            return result.fail().setMsg(e.getMessage());
        }
    }


    /**
     * 扫码支付测试
     */
    @RequestMapping(value = "/scanPay", method = RequestMethod.GET)
    @ResponseBody
    public Result scanPay(HttpServletRequest request, @RequestParam("code") String code, @RequestParam("amount") double amount) {
        Result result = new Result();
        try {

            String outTradeNo = Dates.transDateToStr(new Date(System.currentTimeMillis()), "yyyyMMddHHmmss") + Randoms.getRandomNumr(6); //交易订单号
            String body = "90的便利店"; //body信息
            WechatPayOrderResponse response = new WechatPay().scanCode(code, outTradeNo, body, amount);
            if ("SUCCESS".equals(response.getResult_code())) {
                return result.ok().inject(response);
            } else {
                return result.fail().inject(response);
            }

        } catch (Exception e) {

            log.error("[扫码支付测试异常]", e);
            return result.fail().setMsg("扫码支付测试失败");
        }

    }


}
